/**
 * Created by 小敏哥 on 2017/7/12.
 */
import React, {Component} from 'react'
import {connect} from 'react-redux'
import {Popup, Toast, Modal} from 'antd-mobile'
import FooterAlert from '../../components/remindHome/FooterAlert' //底部弹窗


//actions
import * as carsActions from '../../actions/remindCarAction';

//接口
import CarsServiece from '../../services/CarsServiece';
import YearlyInspectionService from '../../services/YearlyInspectionService';

//常用工具类
import userHelper from '../../utils/userHelper';
import common from '../../utils/common';
import apiHelper from '../../services/apiHelper';
import style from './index.scss';
import urlOperation from '../../utils/urlOperation';

//资源
let progresBoxBg = './images/progresBoxBg.png'; //圆形进度条背景图
let errorMsg = '系统繁忙，请稍后再试';//错误提示信息

class RemindHome extends Component {
    constructor(props) {
        super(props);
        this.host = apiHelper.production ? 'https://annualcheck.cx580.com' : 'http://192.168.1.165:7083';
        this.state = {
            carId: '', //车辆ID
            carNumber: '', //车牌
            registerDate: '', //车辆注册日期（yyyy-MM-dd）
            checkDate: '', //车辆检验日期（yyyy-MM）
            carCode: '', //车身架号
            engineNumber: '', //发动机号
            state: '-1', //年检状态；-1:未知；0：未进入预约期；1：可预约；2：逾期但不足一年；3：逾期且超过一年；4：严重逾期（上线年检）；5报废
            agentFlag: true, //年检类型：true为6年新车年检；false为上线年检
            days: 0, //天数
            orderId: '', //订单id，app年检提醒需要（跟据userType区分渠道）
            orderDetailUrl: '', //订单详情URL（跟据userType区分渠道）
            checkDateText: '', //车辆检验日期（YYYY年MM月DD日）
            beginCheckDateText: '', //开始办理年检的日期（YYYY年MM月DD日）
            isRemind: false, //已预约提醒
            validateFlag: 1, //车牌是否支持年检验证 1：支持年检；0：不支持年检
            validateFlagDone: false, //已经请求过数据
            inspectionValidateMsg: '很抱歉，我们尚未开通您车牌所在地的年检业务！', //不支持年检办理的提示语
            bizFlag: 3,//是否支持办理1:免检；2:上线检；3:不可办理
        };
        this.goToOrderDetail = this.goToOrderDetail.bind(this);
    }

    componentWillMount() {
        /*window.cxyPageResume = function () {
         window.location.reload();
         }*/
    }

    componentDidMount() {
        //获取用户信息
        setTimeout(() => {
            try {
                let postData = {};
                if (navigator.userAgent.indexOf("appname_cxycwz") > -1) {
                    userHelper.getUserIdAndTokenWithCallBack(data => {
                        let {userId, token, carId, carNumber} = data;

                        /*if (!userId || !token) {
                         //未登录
                         userHelper.Login();
                         return;
                         }*/

                        postData = {
                            carId: carId,
                            carNumber: carNumber
                        };

                        common.setViewTitle(decodeURIComponent(postData.carNumber) + '的年检信息');
                        this.getData(postData); //获取数据
                    })
                }
                else {
                    postData = {
                        carId: this.props.params.carId,
                        carNumber: this.props.params.carNumber
                    };
                    common.setViewTitle(decodeURIComponent(postData.carNumber) + '的年检信息');
                    this.getData(postData); //获取数据
                }

                //设置埋点通用数据
                this.cxytjInit(data)

            } catch (error) {
                Toast.info('系统繁忙，请稍后再试', 3, () => common.closeAppView())
            }

        }, 250); //延迟 避免JSDK还未初始化
    }

    componentWillUnmount() {

    }

    toUrl(url) {
        this.context.router.push(url);
    }

    //打开新view跳转
    toUrlByOpenNewView(url) {
        if (navigator.userAgent.indexOf("appname_cxycwz") > -1) {
            //此处增加app用于识别年检提醒
            let finalUrl = `${urlOperation.urlInformation.fullPathname}?detailUserType=app&appType=remind/#${url}`;
            common.openNewBrowserWithURL(finalUrl);
        }
        else {
            this.context.router.push(url);
        }
    }


    //构建跳转地址
    getInspectionUrl() {
        let {carId, carNumber, bizFlag} = this.state;
        let url = `/confirmOrder/${carId}/${carNumber}/${bizFlag}`;
        /*let detailUserType = '';
         let url = '';
         carNumber = encodeURIComponent(carNumber); //url编码
         let t = new Date().getTime();
         if (navigator.userAgent.indexOf("appname_cxycwz") > -1) {
         detailUserType = 'app';
         url = `${this.host}/inspection/index.html?t=${t}&detailUserType=${detailUserType}#/confirmOrder/${carId}/${carNumber}/${bizFlag}`;
         }
         else {
         detailUserType = urlOperation.getParameters().userType;
         let userId = urlOperation.getParameters().userId;
         let userType = urlOperation.getParameters().userType;
         let token = urlOperation.getParameters().token;
         let authType = urlOperation.getParameters().authType;
         url = `${this.host}/inspection/index.html?t=${t}&detailUserType=${detailUserType}&userId=${userId}&userType=${userType}&token=${token}&authType=${authType}#/confirmOrder/${carId}/${carNumber}/${bizFlag}`
         }*/
        return url;
    }

    /**
     * 跳转到办理说明页面
     * @param {*string} url
     */
    toProcessDetail() {
        let {carId, carNumber, validateFlag, validateFlagDone, inspectionValidateMsg, bizFlag} = this.state;

        window.cxytj.recordUserBehavior({
            eventId: 'allInspectionReminder_exit3', //事件标记
            attr1: '办理流程' //属性1
        });

        //判断车牌是否支持年检办理
        /*if (!validateFlagDone) {*/
        this.inspectionValidate(() => {
            let url = this.getInspectionUrl();
            url = encodeURIComponent(url);//url编码

            if (navigator.userAgent.indexOf("appname_cxycwz") > -1) {
                //此处增加app用于识别年检提醒
                let finalUrl = `${urlOperation.urlInformation.fullPathname}?detailUserType=app/#/remindProcessDetail/${url}`;
                common.openNewBrowserWithURL(finalUrl);
            }
            else {
                this.toUrl(`remindProcessDetail/${url}`);
            }
        });
        /*     return;
         } else {
         if (validateFlag != 1) {
         Toast.info(inspectionValidateMsg)
         return;
         }
         }*/


    }

    getData(postData) {
        Toast.loading('', 0);
        CarsServiece.view(postData).then(data => {
            Toast.hide()
            if (data.code == '1000') {
                data = data.data
                if (data.checkDate) { //存在注册时间
                    let checkDateArr = data.checkDate.split('-')

                    if (checkDateArr.length > 1) { //格式合法
                        data.checkDateText = new Date(checkDateArr[0], checkDateArr[1]).toJSON().substr(0, 10) //获取yyyy-MM-dd
                        data.checkDateText = this.showDate(data.checkDateText) //转为yyyy年mm月dd日
                        data.beginCheckDateText = new Date(checkDateArr[0], checkDateArr[1] - 2).toJSON().substr(0, 8) + '01' //获取yyyy-MM-dd
                        data.beginCheckDateText = this.showDate(data.beginCheckDateText, 2) //转为yyyy年mm月
                    }
                }
                data.state += '' //转为字符串
                data.isRemind = data.appointment //是否已经预约
                this.setState(Object.assign({}, this.state, postData, data), () => {
                    this.props.dispatch(carsActions.addCarInfo(this.state)); //提交数据到全局state
                    if (['0', '1', '2', '3'].indexOf(this.state.state) !== -1) {
                        this.clearProgres(); //先重置圆环
                        this.showNumber(this.refs.days, 630, this.state.days, 1500) //动态显示数据
                        this.showProgres(100, Math.ceil((this.state.days / 630) * 100), 1500) //动态显示进度条
                    }
                })
            } else {
                Toast.info(data.msg, 2)
            }
        }, (e) => {
            Toast.hide()
            Toast.info(errorMsg)
        })

    }

    /**
     * 埋点JS
     */
    cxytjInit(data) {
        if (window.cxytjIsReady) { //统计JS已加载完毕
            window.cxytj.init({ //以下为初始化示例，可新增或删减字段
                productId: data.productId || 'allInspectionReminder', //产品ID
                productUserId: data.userid, //APP端 （设备标记ID）
                channel: data.channel || 'App', //推广渠道
                userId: data.accountId, //用户ID
                sessionId: data.sessionId, //会话ID
                longitude: data.lng, //经度
                latitude: data.lat //纬度
            });
            window.cxytj.recordUserBehavior({
                eventId: 'enterAllInspectionReminder', //事件标记
                attr1: '进入年检提醒页面' //属性1
            });
        } else { //统计JS还未加载完毕 但是home组件已经加载完毕
            window.homeReady = () => {
                window.cxytj.init({ //以下为初始化示例，可新增或删减字段
                    productId: data.productId || 'allInspectionReminder', //产品ID
                    productUserId: data.userid, //APP端 （设备标记ID）
                    channel: data.channel || 'App', //推广渠道
                    userId: data.accountId, //用户ID
                    sessionId: data.sessionId, //会话ID
                    longitude: data.lng, //经度
                    latitude: data.lat //纬度
                });
                window.cxytj.recordUserBehavior({
                    eventId: 'enterAllInspectionReminder', //事件标记
                    attr1: '进入年检提醒页面' //属性1
                });
            }
        }
    }

    /**
     * 判断车牌是否支持年检验证
     */
    inspectionValidate(callBack) {
        let {carId, carNumber} = this.state;
        let postData = {
            carId: carId,
            carNumber: carNumber
        };
        Toast.loading('', 0);
        YearlyInspectionService.inspectionValidate(postData).then(data => {
            Toast.hide();
            if (data.code == '1000') {
                data = data.data;
                this.setState({
                    validateFlag: data.validateFlag,//1支持年检 0不支持年检
                    bizFlag: data.bizFlag,//年检类型
                });
                if (data.validateFlag == 1) {
                    //跳转到办理说明页面
                    callBack();
                } else {
                    let inspectionValidateMsg = data.msg || '很抱歉，我们尚未开通您车牌所在地的年检业务！'
                    this.setState({
                        inspectionValidateMsg: inspectionValidateMsg
                    }, () => Toast.info(inspectionValidateMsg))
                }
            } else {
                Toast.info(data.msg)
            }
            this.setState({
                validateFlagDone: true
            }, () => {
                this.props.dispatch(carsActions.updateCarInfo(this.state)); //提交数据到全局state
            })
        }, () => {
            Toast.hide();
            Toast.info(errorMsg)
        })
    }

    /**
     * 获取最新的检验有效期
     */
    getCheckDate() {
        let {carId, carNumber, registerDate, checkDate, carCode, engineNumber} = this.state;

        Toast.loading('', 0);
        let postData = {
            registerDate: registerDate
        };
        YearlyInspectionService.inspectionCheckList(postData).then(data => {
            Toast.hide();
            if (data.code == '1000') {
                data = data.data;
                checkDate = data.dateList[0].checkDate //获取最后一次的检验有效期
                let postData = {
                    carId: carId, //车辆id
                    carNumber: carNumber, //车牌号码
                    registerDate: registerDate, //车辆注册日期
                    checkDate: checkDate, //车辆检验日期
                    carCode: carCode, //车身架号
                    engineNumber: engineNumber, //发动机号
                };
                this.upCarData(postData); //更新车辆信息
            } else {
                Toast.info(data.msg)
            }
        }, () => {
            Toast.hide();
            Toast.info(errorMsg)
        })
    }

    /**
     * 保存预约记录
     */
    addRecord() {
        let {carId, carNumber, checkDate, beginCheckDateText, isRemind} = this.state;
        let appointment_date = beginCheckDateText.replace(/[年|月]/g, '-').replace(/[日]/g, '');

        Toast.loading('', 0);
        let postData = {
            carId: carId, //车辆id
            carNumber: carNumber, //车牌号
            check_date: checkDate, //检验有效期
            appointment_date: appointment_date //预约日期
        };
        YearlyInspectionService.recordAddRecord(postData).then(data => {
            Toast.hide();
            if (data.code == '1000') {
                //预约成功
                if (!isRemind) {
                    this.setState({
                        isRemind: true
                    })
                }

                this.showFooterAlert('2');//显示预约成功

            } else {
                Toast.info(errorMsg)
            }
        }, () => {
            Toast.hide();
            Toast.info(errorMsg)
        })
    }

    /**
     * 更新车辆信息
     */
    upCarData(postData) {
        Toast.loading('', 0);
        CarsServiece.update(postData).then(data => {
            Toast.hide();
            if (data.code == '1000') {
                data = data.data;

                if (data.checkDate) { //存在注册时间
                    console.log("存在注册时间");
                    let checkDateArr = data.checkDate.split('-');

                    if (checkDateArr.length > 1) { //格式合法
                        console.log("格式合法");
                        data.checkDateText = new Date(checkDateArr[0], checkDateArr[1]).toJSON().substr(0, 10);//获取yyyy-MM-dd
                        data.checkDateText = this.showDate(data.checkDateText); //转为yyyy年mm月dd日
                        data.beginCheckDateText = new Date(checkDateArr[0], checkDateArr[1] - 2).toJSON().substr(0, 8) + '01' //获取yyyy-MM-dd
                        data.beginCheckDateText = this.showDate(data.beginCheckDateText, 2);//转为yyyy年mm月
                    }
                }
                data.state += ''; //转为字符串
                data.isRemind = data.appointment; //是否已经预约
                this.setState(Object.assign({}, this.state, postData, data), () => {
                    this.props.dispatch(carsActions.updateCarInfo(this.state)); //提交数据到全局state

                    this.clearProgres(); //先重置圆环
                    this.showNumber(this.refs.days, 630, this.state.days, 1500);//动态显示数据
                    this.showProgres(100, Math.ceil((this.state.days / 630) * 100), 1500) //动态显示进度条
                })
            } else {
                Toast.info(data.msg)
            }
        }, () => {
            Toast.hide();
            Toast.info(errorMsg)
        })
    }

    getOrderDetailUrl(data, callBack) {
        Toast.loading('', 0);
        CarsServiece.getOrderDetail(data).then((result) => {
            Toast.hide();
            if (result.code == '1000') {
                callBack(result.data.uri);
            }
            else {
                Toast.info(result.msg)
            }
        })
    }

    /**
     * 动态显示数字
     * @param {*object} e dom对象
     * @param {*number} start 开始时数字
     * @param {*number} end 结束时数字
     * @param {*number} 速度 多少毫秒完成 默认1000毫秒
     */
    showNumber(e, start, end, ms = 1000) {
        let end_ms = ms - 200; //结束的时间提前200毫秒
        ms = Math.floor(ms / Math.abs(end - start))
        let delNum = 1 //每次应该减的数字
        if (ms < 4) {
            delNum = Math.floor(4 / ms)
        }
        console.log("最终的数字：", end)
        let timeId = setInterval(() => {
            try {
                if (start < end) {
                    start += delNum; //由小变大
                    if (start >= end) {
                        clearInterval(timeId)
                    }
                } else {
                    start -= delNum; //由大变小
                    if (start <= end) {
                        clearInterval(timeId)
                    }
                }

                e.innerHTML = parseInt(start)
            } catch (error) {
                clearInterval(timeId)
            }

        }, ms);

        setTimeout(function () {
            clearInterval(timeId);
            e.innerHTML = parseInt(end)
        }, end_ms)
    }

    /**
     * 动态显示进度条
     * @param {*number} start 开始时进度 0-100
     * @param {*number} end 结束时进度 0-100
     * @param {*number} 速度 多少毫秒完成 默认1000毫秒
     */
    showProgres(start, end, ms = 1000) {
        ms = Math.floor(ms / Math.abs(end - start))
        let clientWidth = document.documentElement.clientWidth
        clientWidth = clientWidth > 540 ? 540 : clientWidth
        let bl = clientWidth / 375

        if (start < end) {
            //从小到大
        } else {
            //从大到小
            let iLeft = 0; //控制左边 占比35%
            let iTop = 0; //控制上边 占比30%
            let iRight = 0; //控制右边 占比35%

            let leftBottom = 0; //左边的bottom

            let timeId = setInterval(() => {
                try {
                    --start;
                    if (start >= 64) {
                        //大于60%
                        ++iRight;
                        this.refs.grayCircularBoxRight.style.top = (172 - iRight * Math.floor(143 / 35)) + 'px'
                        if (start === 64) {
                            this.refs.grayCircularBoxRight.style.top = '0px' //避免还存在多余的进度
                        }
                    } else if (start >= 34) {
                        //大于60%
                        ++iTop;
                        this.refs.grayCircularBoxTop.style.width = (iTop * Math.ceil(112 / 30)) + 'px'
                    } else {
                        ++iLeft;
                        leftBottom = (143 - (iLeft * Math.ceil(143 / 35)))
                        leftBottom = leftBottom < 6 ? 6 : leftBottom //
                        this.refs.grayCircularBoxLeft.style.bottom = leftBottom + 'px'
                    }
                    if (start <= end) {
                        clearInterval(timeId)
                    }
                } catch (error) {
                    clearInterval(timeId)
                }
            }, ms)
        }
    }

    /**
     * 还原进度条
     */
    clearProgres() {
        this.refs.grayCircularBoxRight.style.top = '';
        this.refs.grayCircularBoxTop.style.width = '';
        this.refs.grayCircularBoxLeft.style.bottom = '';
    }

    /**
     * 显示日期 年月||年月日
     * @param {*date} date 日期 格式：YYYY-MM-DD
     * @param {*string} type 日期类型 1、年月入；2、年月；    默认等于年月日
     */
    showDate(date, type = '1') {
        let arr = date.split('-');
        if (arr.constructor !== Array || arr.length < 3) {
            return date; //格式不合法 返回原数据
        }
        switch (type) {
            case '1':
                date = arr[0] + '年' + arr[1] + '月' + arr[2] + '日';
                break;
            case '2':
                date = arr[0] + '年' + arr[1] + '月';
                break;
            default:
                date = arr[0] + '年' + arr[1] + '月' + arr[2] + '日';
        }
        return date
    }

    /**
     * 显示底部弹窗
     */
    showFooterAlert(type = '1') {
        let {days, isRemind} = this.state;

        let props = {
            days: days, //天数
            type: type,//底部弹窗类型：1、未到年检周期。2、预约成功
            isRemind: isRemind, //已预约提醒
            close: () => Popup.hide(),
            clickBtn: btn => {
                Popup.hide(); //隐藏

                if (type == '1') {
                    if (btn == 'leftBtn') {
                        window.cxytj.recordUserBehavior({
                            eventId: 'allInspectionReminder_exit8', //事件标记
                            attr1: '底部弹窗—继续办理' //属性1
                        });
                        this.toProcessDetail(); //跳转到办理说明页
                    } else if (btn == 'rightBtn') {
                        if (!isRemind) {
                            //未预约过短信提醒
                            this.addRecord(); //预约提醒
                        }
                        window.cxytj.recordUserBehavior({
                            eventId: 'allInspectionReminder_event5', //事件标记
                            attr1: isRemind ? '底部弹窗—暂不办理' : '底部弹窗—短信通知' //属性1
                        });
                    }

                } else {
                    // console.log("预约成功: 点击了：", btn)
                }
            }
        };
        Popup.show(<FooterAlert {...props} />, {animationType: 'slide-up'}
        );
    }

    /**
     * 判断是否已经登录
     */
    checkLogin(state) {
        window.cxytj.recordUserBehavior({
            eventId: 'allInspectionReminder_event4', //事件标记
            attr1: '立即办理—底部弹窗' //属性1
        });
        userHelper.getUserIdAndTokenWithCallBack(data => {
            let {userId, token,} = data;

            /*if (!userId || !token) {
             //未登录
             window.cxytj.recordUserBehavior({
             eventId: 'allInspectionReminder_exit5', //事件标记
             attr1: '立即办理—登录注册' //属性1
             });
             userHelper.Login()
             } else {*/
            if (state == '-1') { //补充年检资料
                let {carId, carNumber} = this.state;
                this.toUrl(`/calculatorOfYearlyCheck/${carNumber}/${carId}`);
                window.cxytj.recordUserBehavior({
                    eventId: 'allInspectionReminder_exit7', //事件标记
                    attr1: '补充年检资料' //属性1
                });
            } else if (state == '0') {
                this.showFooterAlert(); //未进入预约期
            } else {
                window.cxytj.recordUserBehavior({
                    eventId: 'allInspectionReminder_exit6', //事件标记
                    attr1: '立即办理—现有流程' //属性1
                });
                this.toProcessDetail(); //跳转到办理说明页
            }
            //}

        })
    }

    /**
     * 计算有误
     */
    calculation() {
        let {carId, carNumber} = this.state;
        alert('1');
        this.toUrl(`/calculatorOfYearlyCheck/${carNumber}/${carId}`);
        window.cxytj.recordUserBehavior({
            eventId: 'allInspectionReminder_exit2', //事件标记
            attr1: '计算有误' //属性1
        });
    }

    /**
     * 获取页面色系
     * @param {*number} state 状态
     */
    getColor(state) {
        let color = style.homeRed;

        if (state == '-1') {
            color = style.homeGray
        } else if (state == '0') {
            color = ''; //默认颜色 所以不需要修改
        } else if (state == '1') {
            color = style.homeBlue
        } else if (state == '6') {
            color = style.homeBlue
        }

        return color
    }

    /**
     * 渲染文字提醒
     */
    getHomeMsgBox(state) {
        let {beginCheckDateText, bizFlag} = this.state;

        let jsxArr = { //年检状态；-1:未知；0：未进入预约期；1：可预约；2：逾期但不足一年；3：逾期且超过一年；4：严重逾期（上线年检）；5报废
            '-1': <div className={style.homeMsgBox}>
                <div>请补充车辆信息后查看年检状态</div>
                <p>逾期状态下，被查将扣车扣分并在事故中不能出险</p>
            </div>,
            '0': <div className={style.homeMsgBox}>
                <div>目前尚无需进行年检，可放心驾驶</div>
                <p>您可于 {beginCheckDateText} 起进行年检办理</p>
            </div>,
            '1': <div className={style.homeMsgBox}>
                <div>车辆已进入年检周期，请尽快办理</div>
                <p>逾期后驾驶被查将扣车扣分并在事故中不能出险</p>
            </div>,
            '2': <div className={style.homeMsgBox}>
                <div>该车辆年检已逾期，请您尽快办理</div>
                <p>逾期超过一年时必须办理上线检，<br />逾期车辆出事故不能报保险，上路被查将扣车扣分</p>
            </div>,
            '3': <div className={style.homeMsgBox}>
                <div>车辆年检已逾期一年，需上线检测</div>
                <p>逾期超过一年时必须办理上线检，<br />逾期车辆驾驶被查将扣车扣分并在事故中不能出险</p>
            </div>,
            '4': <div className={style.homeMsgBox}>
                <div>年检逾期已连续两次，请尽快处理</div>
                <p>请您在“下一个年检有效期之内”完成车辆上线检测<br />否则车辆将直接报废！</p>
            </div>,
            '5': <div className={style.homeMsgBox}>
                <div>年检逾期已连续三次，需强制报废</div>
                <p>请勿驾驶该车辆上路，被查时将收缴车辆<br />并面临罚款和吊销驾驶证的处罚</p>
            </div>,
            '6': <div className={style.homeMsgBox}>
                <div>我们正在办理您的年检订单</div>
                <p>详细信息可在订单详情中查看</p>
            </div>
        };
        if ((state == 2 || state == 3) && bizFlag == 2) {
            //过线检需要有特殊的提示显示
            return <div className={style.homeMsgBox}>
                <div>该车辆已逾期{this.state.days}天，需上线检测</div>
                <p>逾期超过一年时必须办理上线检，<br />逾期车辆驾驶被查将扣车扣分并在事故中不能出险</p>
            </div>
        }
        else {
            return jsxArr[state] || jsxArr['-1']
        }
    }

    //根据获取的detail地址跳转到相应的目录
    goToOrderDetail() {
        window.cxytj.recordUserBehavior({
            eventId: 'allInspectionReminder_exit9', //事件标记
            attr1: '继续办理年检' //属性1
        });
        this.getOrderDetailUrl({orderId: this.state.orderId}, (uri) => {
            /*let detailUserType = urlOperation.getParameters().userType;
             let userId = urlOperation.getParameters().userId;
             let userType = urlOperation.getParameters().userType;
             let token = urlOperation.getParameters().token;
             let authType = urlOperation.getParameters().authType;
             let url=`${this.host}/inspection/index.html?detailUserType=${detailUserType}&userId=${userId}&userType=${userType}&token=${token}&authType=${authType}#/${uri}`;
             common.openNewBrowserWithURL(url)*/
            this.toUrlByOpenNewView('/' + uri);
        })
    }

    /**
     * 渲染底部按钮
     */
    showFooterBtn(state) {
        let {isRemind, bizFlag} = this.state;
        let btn = '';

        if (state == '6') {
            btn = <div className={style.btnWhite} onClick={this.goToOrderDetail}>继续办理年检</div>
        } else if (state == '-1') {
            btn = <div className={style.btn} onClick={() => this.checkLogin(state)}>补充年检资料</div>
        } else if (bizFlag != 3) {
            btn =
                <div className={style.btn} onClick={() => this.checkLogin(state)}>立即办理{isRemind ? ' (已预约提醒)' : ''}</div>
        } else {
            btn = <div className={style.btn + ' ' + style.notClickBtn}>立即办理</div>
        }
        return btn
    }

    /**
     * 点击常见问题
     */
    clickProgresIssue() {
        /*let detailUserType='';
         let url='';
         if (navigator.userAgent.indexOf("appname_cxycwz") > -1) {
         detailUserType = 'app';
         url = `${this.host}/inspection/index.html?detailUserType=${detailUserType}/#/questions`;
         }
         else {
         detailUserType = urlOperation.getParameters().userType;
         let userId = urlOperation.getParameters().userId;
         let userType = urlOperation.getParameters().userType;
         let token = urlOperation.getParameters().token;
         let authType = urlOperation.getParameters().authType;
         url = `${this.host}/inspection/index.html?detailUserType=${detailUserType}&userId=${userId}&userType=${userType}&token=${token}&authType=${authType}/#/questions`
         }*/
        if (navigator.userAgent.indexOf("appname_cxycwz") > -1) {
            //此处增加app用于识别年检提醒
            let finalUrl = `${urlOperation.urlInformation.fullPathname}?detailUserType=app/#/questions`;
            common.openNewBrowserWithURL(finalUrl);
        }
        else {
            this.toUrl('/questions');
        }

        window.cxytj.recordUserBehavior({
            eventId: 'allInspectionReminder_exit4', //事件标记
            attr1: '常见问题' //属性1
        });
        //  common.openNewBrowserWithURL(url)
    }

    /**
     * 点击更新信息
     */
    clickDateMsg() {
        window.cxytj.recordUserBehavior({
            eventId: 'allInspectionReminder_event2', //事件标记
            attr1: '点击更新年检信息' //属性1
        });

        Modal.alert('确认已办理过本次年检？', '确认后将为您重新计算', [
            {
                text: '取消', onPress: () => false, style: {color: '#108ee9'}
            },
            {
                text: '确认', onPress: () => {
                window.cxytj.recordUserBehavior({
                    eventId: 'allInspectionReminder_event3', //事件标记
                    attr1: '确认更新年检信息' //属性1
                });
                this.getCheckDate()
            }, style: {color: '#108ee9'}
            },
        ])

    }

    showIconPromptToast(state) {
        window.cxytj.recordUserBehavior({
            eventId: 'allInspectionReminder_event1', //事件标记
            attr1: '查看逾期详细说明' //属性1
        });
        let {days} = this.state;
        let toasts = {
            '2': `车辆未按规定在检验有效期内完成年检，目前已逾期${days}天。请您尽快处理，否则逾期超过一年，将需要车主本人开车去车管所亲自办理。`,
            '3': `车辆未按规定在检验有效期内完成年检，目前已逾期${days}天。按相关法律规定，需要车主本人开车去车管所亲自办理年检。`,
            '4': `车辆已连续两次年检逾期，请您在“下一次理论上的年检有效期”之内完成车辆上线检测，否则车辆将直接报废。`,
            '5': `车辆未按规定在检验有效期内完成年检，并且逾期次数已连续超过3次。按我国机动车相关法规《机动车强制报废标准》的规定，车辆已达强制报废条件。请勿再驾驶此车上路，否则将被收缴，并面临罚款和吊销驾驶证的处罚`
        };
        if (toasts[state]) {
            Toast.info(toasts[state])
        }
    }

    render() {
        console.log("this.state", this.state);
        let {state, checkDateText, beginCheckDateText} = this.state;

        let color = this.getColor(state);//获取颜色
        let texts = { //年检状态；-1:未知；0：未进入预约期；1：可预约；2：逾期但不足一年；3：逾期且超过一年；4：严重逾期（上线年检）；5报废；6年审订单办理中
            '-1': <i>小心年检逾期</i>,
            '0': <i>距年检可预约天数</i>,
            '1': <i>距年检有效期截止还剩天数</i>,
            '2': <i className={style.iconPromptI} onClick={() => this.showIconPromptToast(state)}>该车辆已逾期天数</i>,
            '3': <i className={style.iconPromptI} onClick={() => this.showIconPromptToast(state)}>该车辆已逾期天数</i>,
            '4': <i className={style.iconPromptI} onClick={() => this.showIconPromptToast(state)}>该车辆存在报废风险</i>,
            '5': <i className={style.iconPromptI} onClick={() => this.showIconPromptToast(state)}>请勿上路驾驶</i>,
            '6': <i><span style={{fontWeight: 'normal'}}>请您耐心等待</span></i>
        }
        let daysTexts = {
            '-1': '状态未知',
            '0': '',
            '1': '',
            '2': '',
            '3': '',
            '4': '严重逾期',
            '5': '车辆已报废',
            '6': '年检办理中'
        };

        let daysClassName = ['0', '1', '2', '3'].indexOf(state) !== -1 ? '' : style.font60;

        return (
            <div className={style.box}>
                <div className={style.homeBox + " " + color}>
                    <div className={style.homeTop}>
                        {state == '-1' ? <p style={{height: '.36rem'}}></p> :
                            <p>检验有效期截止至 — {checkDateText}
                                {state == '6' ? '' :
                                    <span onClick={() => this.calculation()}>计算有误</span>
                                }
                            </p>
                        }
                    </div>
                    <div className={style.progresBox}>

                        {/*显示天数或对应的年检状态icon start*/}
                        <div className={style.progres} style={{backgroundImage: `url(${progresBoxBg})`}}>
                            <div className={style.progresDaysBox}>
                                <span ref='days' className={daysClassName}>{daysTexts[state]}</span>{texts[state]}
                            </div>
                            <span className={style.progresIssue} onClick={() => this.clickProgresIssue()}>常见问题</span>
                        </div>
                        {/*显示天数或对应的年检状态icon end*/}

                        {/*渐变圆环 start*/}
                        <div className={style.circularBox}>
                            <div className={style.circular1Box}>
                                <div className={style.circular + ' ' + style.circular1}>
                                    <div className={style.hideCircular}></div>
                                </div>
                            </div>
                            <div className={style.circular + ' ' + style.circular2}>
                                <div className={style.hideCircular}></div>
                            </div>
                            <div className={style.whiteCircular}></div>
                            <div className={style.grayCircularBox}>
                                <div ref='grayCircularBoxLeft' className={style.grayCircularBoxLeft}></div>
                                <div ref='grayCircularBoxTop' className={style.grayCircularBoxTop}></div>
                                <div ref='grayCircularBoxRight' className={style.grayCircularBoxRight}></div>
                            </div>
                        </div>
                        {/*渐变圆环 start*/}

                    </div>

                    {/*文字提醒 start*/}
                    {this.getHomeMsgBox(state)}
                    {/*文字提醒 end*/}

                    {/*立即办理按钮 || 查看订单详情按钮 start*/}
                    <div className={style.buttonContainer}>
                        {this.showFooterBtn(state)}
                    </div>
                    {/*立即办理按钮 || 查看订单详情按钮 end*/}

                    {/*已办理过年检 更新按钮 start*/}
                    {
                        ['1', '2', '3', '4', '5'].indexOf(state) != -1 ?
                            <div className={style.homeBtnBottom}>已办理过本次年检？ <span
                                onClick={() => this.clickDateMsg()}>点击更新信息</span></div>
                            :
                            ''
                    }
                    {/*已办理过年检 更新按钮 end*/}
                </div>
                <div className={style.homeFooter}>
                    <p>年检数据由当地车管所提供，服务由广东邮政提供<br />数据更新有延时，最终以当地车管所为准</p>
                </div>

            </div>
        )
    }
}

//使用context
RemindHome.contextTypes = {
    router: React.PropTypes.object.isRequired
};

export default connect()(RemindHome);